package Fly.example.controller;


import Fly.example.common.R;
import Fly.example.dto.DishDto;
import Fly.example.dto.SetmealDto;
import Fly.example.pojo.*;
import Fly.example.service.ICategoryService;
import Fly.example.service.ISetmealDishService;
import Fly.example.service.ISetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 前端控制器
 * </p>
 *
 * @author 陽Fly
 * @since 2025-06-14
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private ISetmealService setmealService;
    @Autowired
    private ISetmealDishService setmealDishService;
    @Autowired
    private ICategoryService categoryService;

    //查询列表数据
    @GetMapping("/page")
    public R<Page<SetmealDto>> getSetmeal(Integer page, Integer pageSize,String name) {
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> Lastpage = new Page<>();
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null,Setmeal::getName, name);
        //添加排序条件
        wrapper.orderByDesc(Setmeal::getPrice).orderByAsc(Setmeal::getCreateTime);
        setmealService.page(pageInfo, wrapper);
        //拷贝对象
        BeanUtils.copyProperties(pageInfo, Lastpage,"records");
        List<Setmeal> records = pageInfo.getRecords();
        //进行处理
        List<SetmealDto> list = records.stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            //获取分类的id
            Long categoryId = item.getCategoryId();
            //根据分类的id进行查询，然后设置categoryName
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();//分类名称
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        //单独进行赋值
        Lastpage.setRecords(list);
        return R.success(Lastpage);
    }

    //新增套餐业务
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)//删除所有套餐的缓存
    public R<String> addSetmeal(@RequestBody SetmealDto setmealDto) {
        log.info("新增业务开始…………");
        log.info("套餐的信息为：{}", setmealDto);
        setmealService.savaWithStemeal(setmealDto);
        return R.success("新增套餐成功");
    }

    //修改套餐的数据回显，根据di查询信息，用于页面的数据展示
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id){
        log.info("需要回显的数据的id为：{}",id);
        //先得到菜品的信息
        Setmeal setmeal = setmealService.getById(id);
        //创建DTO对象，等下要返回的数据就是这个对象
        SetmealDto setmealDto = new SetmealDto();
        //将查询到的信息复制到DTO里
        BeanUtils.copyProperties(setmeal,setmealDto);
        //获取id
//        Long categoryId = setmeal.getCategoryId();
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(wrapper);
        setmealDto.setSetmealDishes(list);
        return R.success(setmealDto);
    }

    //修改套餐
    @PutMapping
    @Transactional//添加事务管理
    @CacheEvict(value = "setmealCache",allEntries = true)//删除所有套餐的缓存
    public R<String> set(@RequestBody SetmealDto setmealDto) {
        log.info("修改套餐业务开始…………");
        //获取口味的信息
        if (setmealDto != null) {
            List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
            log.info("前端传过来的信息为：{}", setmealDishes);
            Setmeal setmeal = new Setmeal();
            //复制信息并更新setmeal的信息
            BeanUtils.copyProperties(setmealDto,setmeal);
            log.info("stemeal信息为：{}",setmeal);
            setmealService.updateById(setmeal);
            //使用stream流来设置setmealId的值
            List<SetmealDish> list = setmealDishes.stream().map(item -> {
                //设置setmealId的值
                item.setSetmealId(String.valueOf(setmeal.getId()));
                //返回
                return item;
            }).collect(Collectors.toList());
            //先根据id删除对应的值，然后再保存值，以此来得到更新的操作
            //删除
            LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SetmealDish::getSetmealId,setmeal.getId());
            setmealDishService.remove(wrapper);
            //添加
            setmealDishService.saveBatch(list);
        }

        return R.success("修改套餐信息成功");
    }

    //删除以及批量删除
    @Transactional//添加事务管理
    @DeleteMapping("")
    @CacheEvict(value = "setmealCache",allEntries = true)//删除所有套餐的缓存
    public R<String> del(String ids){
        log.info("删除业务开始…………");
        String[] split = ids.split(",");
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,split);
        List<Setmeal> list = setmealService.list(queryWrapper);
        //判断当前套餐的状态，如果有正在售卖的就结束方法，返回错误信息
        for (Setmeal setmeal : list) {
            if (setmeal.getStatus() == 1){
                return R.error("当前所选择的套餐有正在售卖状态，不能删除");
            }
        }
        LambdaQueryWrapper<Setmeal> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(Setmeal::getId,split);
        LambdaQueryWrapper<SetmealDish> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.in(SetmealDish::getSetmealId,split);
        setmealService.remove(wrapper1);
        setmealDishService.remove(wrapper2);
        return R.success("删除成功");
    }

    //停售-起售，批量停起
    @PostMapping("/status/{status}")
    public R<String> setStatus(@PathVariable Integer status,String ids){
        log.info("要修改的id为：{}，要修改的状态为{}",ids,status);
        //构造一个实体类进行更新
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);
        String[] split = ids.split(",");
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,split);
        //进行更新操作
        setmealService.update(setmeal,wrapper);
        return R.success("修改状态成功");
    }

    //用于套餐新增页面数据回显，根据category_id查询
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> see(Setmeal setmeal) {
        log.info("setmeal_id为{}",setmeal.getCategoryId());
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId())
        .eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        List<Setmeal> list = setmealService.list(wrapper);
        return R.success(list);
    }
}
